﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Reflection;
using System.ComponentModel;

namespace DotNetX
{
    public static class EnumExtensions
    {
        public static StringDictionary ToStringDictionary(Type t)
        {
            if (!t.IsEnum)
                return null;

            var vals = Enum.GetValues(t).Cast<int>().ToList();
            var names = Enum.GetNames(t);

            StringDictionary sd = new StringDictionary();

            for (int i = 0; i < vals.Count && i < names.Length; i++)
            {
                sd.Add(names[i], vals[i].ToString());
            }

            return sd;
        }

        public static string GetDescription(this Enum e)
        {
            // from http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx
            Type type = e.GetType();

            MemberInfo[] memInfo = type.GetMember(e.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return e.ToString();
        }
    }
}
